//package com.plian.system.service.hr.recruitment.impl;
//
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.fasterxml.jackson.core.type.TypeReference;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.cache.UserCache;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.constant.yth.YthConstant;
//import com.plian.system.entity.hr.recruitment.RemovalManagement;
//import com.plian.system.entity.hr.recruitment.RemovalPartTimeInfo;
//import com.plian.system.entity.hr.staff.StaffFiles;
//import com.plian.system.entity.sys.ApprovalMessage;
//import com.plian.system.enumeratea.PartTimeStatus;
//import com.plian.system.mapper.hr.recruitment.PartTimeInfoMapper;
//import com.plian.system.mapper.hr.recruitment.PartTimeManagementMapper;
//import com.plian.system.mapper.hr.recruitment.RemovalManagementMapper;
//import com.plian.system.mapper.hr.recruitment.RemovalPartTimeInfoMapper;
//import com.plian.system.mapper.hr.staff.StaffFilesMapper;
//import com.plian.system.mapper.sys.DictMapper;
//import com.plian.system.model.R;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.service.hr.recruitment.INewPartTimeManagementService;
//import com.plian.system.service.hr.recruitment.INewRemovalManagementService;
//import com.plian.system.service.hr.recruitment.IPartTimeInfoService;
//import com.plian.system.service.hr.recruitment.IRemovalPartTimeInfoService;
//import com.plian.system.service.hr.staff.IStaffFilesService;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.sys.file.FileService;
//import com.plian.system.service.sys.message.IApprovalMessageService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.vo.hr.recruitment.RemovalManagementVO;
//import com.plian.system.vo.yth.YthResult;
//import com.plian.system.wrapper.hr.recruitment.PartTimeManagementWrapper;
//import com.plian.system.wrapper.hr.recruitment.RemovalManagementWrapper;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
///**
// * 服务实现类
// *
// * @author BladeX
// * @since 2019-12-03
// */
//@Slf4j
//@Service
//@AllArgsConstructor
//public class NewRemovalManagementServiceImpl extends BaseServiceImpl<RemovalManagementMapper, RemovalManagement> implements INewRemovalManagementService, BaseFlowService {
//
//
//    private IPartTimeInfoService partTimeInfoService;
//
//    private FormWorkflowService formWorkflowService;
//
//    private IFormCodeService formCodeService;
//
//    private RemovalManagementWrapper removalManagementWrapper;
//
//    private PartTimeInfoMapper partTimeInfoMapper;
//
//    private PartTimeManagementWrapper partTimeManagementWrapper;
//
//    private PartTimeManagementMapper partTimeManagementMapper;
//
//    private INewPartTimeManagementService partTimeManagementService;
//
//    private IRemovalPartTimeInfoService removalPartTimeInfoService;
//
//    private RemovalPartTimeInfoMapper removalPartTimeInfoMapper;
//
//    private IStaffFilesService staffFilesService;
//
//    private DictMapper dictMapper;
//
//    private FileService fileService;
//
//    private IApprovalMessageService approvalMessageService;
//
//    private final IOrgService orgService;
//
//    private final StaffFilesMapper staffFilesMapper;
//
//
//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public Boolean submit(RemovalManagement removalManagement) {
//        boolean result = saveOrUpdate(removalManagement);
//        //免职信息
//        List<RemovalPartTimeInfo> removePartTimeInfos = removalManagement.getRemovePartTimeInfos();
//        if (CollectionUtil.isNotEmpty(removePartTimeInfos)) {
//            removePartTimeInfos.forEach(item -> {
//                if (item.getId() == null) {
//                    item.setStaffNameId(removalManagement.getStaffNameId());
//                    item.setRemoveManagementId(removalManagement.getId());
//                    item.setStatus(PartTimeStatus.REMOVAL_AUDIT.getStatus());
//                }
//            });
//            removalPartTimeInfoService.saveList(removePartTimeInfos);
//        }
//
//        return result;
//    }
//
//    @Override
//    public R detail(RemovalManagement detail) {
//
//        RemovalManagement currRemovalManagement = getById(detail.getId());
//        if (!Optional.ofNullable(currRemovalManagement).isPresent()) {
//            return R.fail();
//        }
//        RemovalManagementVO removalManagementVO = removalManagementWrapper.entityToVO(currRemovalManagement);
//
//        if (!Optional.ofNullable(removalManagementVO).isPresent()) {
//            return R.fail();
//        }
//        PageData pd = new PageData();
//        ObjectMapper mapper = new ObjectMapper();
//        String json = JSON.toJSONStringWithDateFormat(removalManagementVO, DateUtil.PATTERN_DATETIME);
//        try {
//            pd.putAll(mapper.readValue(json, new TypeReference<HashMap<String, String>>() {
//            }));
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return R.error();
//        }
//        //已兼职
//        pd.put("partTimeInfos", partTimeManagementService.selectPartTimeInfoStatus(removalManagementVO.getStaffNameId(),
//                PartTimeStatus.INCUMBENCY.getStatus()));
//        //拟免职
//        pd.put("removePartTimeInfos", removalPartTimeInfoService.selectRemovalPartTimeInfoStatus(currRemovalManagement,
//                PartTimeStatus.REMOVAL_AUDIT.getStatus()));
//        return R.data(pd);
//    }
//
//    @Override
//    public boolean saveOrUpdate(RemovalManagement removalManagement) {
//        boolean flag = false;
//        if (!Optional.ofNullable(removalManagement.getId()).isPresent()) {
//            removalManagement.setVersion("1");
//            removalManagement.setCode(formCodeService.getCode(FormTypeConstant.HR_REMOVAL_FORM));
//            removalManagement.setFormType(String.valueOf(FormTypeConstant.HR_REMOVAL_FORM));
//            flag = true;
//        }
//        boolean result = super.saveOrUpdate(removalManagement);
//        if (flag) {
//            fileService.saveAll(String.valueOf(removalManagement.getId()), removalManagement.getDocList());
//        } else {
//            fileService.edit(String.valueOf(removalManagement.getId()), removalManagement.getDocList());
//        }
//        return result;
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            RemovalManagement removalManagement = getById(id);
//            if (removalManagement == null) {
//                return false;
//            } else if (removalManagement.getStatus() != null &&
//                    (removalManagement.getStatus() != FormStatusConstant.STASH && removalManagement.getStatus() != FormStatusConstant.UNREVIEWED)) {
//                return false;
//            }
//            formWorkflowService.deleteProcessInstance(String.valueOf(id));
//            partTimeInfoService.changeStatusById(removalManagement.getId(), PartTimeStatus.INCUMBENCY.getStatus());
//        }
//        return super.deleteLogic(ids);
//    }
//
//    @Override
//    public HashMap<String, Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW, "提交");
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String, Object>();
//    }
//
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH, "审批完成");
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//        return handleStatus(Long.valueOf(id), formState, comment);
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED, null);
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        LambdaQueryWrapper<RemovalManagement> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.in(RemovalManagement::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//        List<RemovalManagement> recruitmentManagements = list(queryWrapper);
//        List<RemovalManagementVO> recruitmentManagementVOS = removalManagementWrapper.entityToVO(recruitmentManagements);
//        List<PageData> pageDataList = new ArrayList<>();
//        try {
//            if (CollectionUtil.isNotEmpty(recruitmentManagementVOS)) {
//                for (RemovalManagementVO vo : recruitmentManagementVOS) {
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", vo.getCompanyName());
//                    pd.put("APPLICANTNAME", vo.getCreateUserName());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", vo.getCompanyNameId());
//                    pd.put("formType", FormTypeConstant.HR_REMOVAL_FORM);
//                    pd.put("orgName", vo.getCompanyName());
//                    pageDataList.add(pd);
//                }
//            }
//
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FormTypeConstant.HR_REMOVAL_FORM);
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     *
//     * @param id           主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus, String comment) {
//        try {
//            RemovalManagement removalManagement = getById(id);
//            if (updateStatus == FormStatusConstant.FINISH) {
//                removalManagement.setApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                removalManagement.setApprovedTime(now);
//                //将免职人员信息status改变 status = 4
//                removalPartTimeInfoService.updateStatus(removalManagement, PartTimeStatus.REMOVAL.getStatus());
//                //将对应兼职表的状态也改变 status = 4
//                List<RemovalPartTimeInfo> removalPartTimeInfos = removalPartTimeInfoMapper.selectList(new LambdaQueryWrapper<RemovalPartTimeInfo>()
//                        .eq(RemovalPartTimeInfo::getRemoveManagementId, removalManagement.getId()));
//                if (CollectionUtil.isNotEmpty(removalPartTimeInfos)){
//                    List<Long> partTimeInfoIds = removalPartTimeInfos.stream().map(RemovalPartTimeInfo::getPartTimeInfoId).collect(Collectors.toList());
//                    partTimeInfoService.changeStatusByRemove(partTimeInfoIds, PartTimeStatus.REMOVAL.getStatus());
//                }
//            }
//            removalManagement.setStatus(updateStatus);
//
//            if (YthConstant.DATA_NINGBO.equals(removalManagement.getDataSource())) {
//                if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT) {
//                    ApprovalMessage approvalMessage = new ApprovalMessage();
//                    approvalMessage.setDataSourceId(removalManagement.getDataSourceId());
//                    approvalMessage.setOpinion(comment);
//                    approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
//                    approvalMessage.setIsSend(1);
//                    approvalMessage.setFilingCode(removalManagement.getFilingCode());
//                    approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
//                    approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
//                    approvalMessage.setFormType(Integer.valueOf(removalManagement.getFormType()));
//                    approvalMessageService.save(approvalMessage);
//                }
//            }
//
//
//            updateById(removalManagement);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public String saveRemoveManagementReform(String data) {
//        YthResult ythResult = new YthResult();
//        //成功的id集合
//        List<String> successIds = new ArrayList<>();
//        //失败的id集合
//        List<String> failIds = new ArrayList<>();
//        //失败的原因
//        List<String> failReasons = new ArrayList<>();
//        //将json字符串转换成list
//        List<RemovalManagement> dataList = JSON.parseArray(data, RemovalManagement.class);
//        //判断list是否为空
//        if (CollectionUtil.isNotEmpty(dataList)) {
//            //根据datasourceIds 查询出所有的数据
//            List<RemovalManagement> list = list(new LambdaQueryWrapper<RemovalManagement>()
//                    .in(RemovalManagement::getDataSourceId, dataList.stream()
//                            .map(RemovalManagement::getDataSourceId).toArray()));
//            //如果数据库中有数据，就更新，没有就新增
//            for (RemovalManagement entity : dataList) {
//                String dataSourceId = entity.getDataSourceId();
//                if (CollectionUtil.isNotEmpty(list)) {
//                    List<String> olIds = list.stream().map(RemovalManagement::getDataSourceId).collect(Collectors.toList());
//                    //判断数据库中是否有数据
//                    if (olIds.contains(dataSourceId)) {
//                        for (RemovalManagement oldEntity : list) {
//                            if (dataSourceId.equals(oldEntity.getDataSourceId())) {
//                                successIds.add(dataSourceId);
//                                entity.setId(oldEntity.getId());
//                                entity.setDataSource(YthConstant.DATA_NINGBO);
//
//                                extracted(entity);
//
//                                submit(entity);
//                                list.remove(oldEntity);
//                                break;
//                            }
//                        }
//                    } else {
//                        //如果数据库中没有数据，就新增
//                        entity.setDataSource(YthConstant.DATA_NINGBO);
//
//                        extracted(entity);
//
//                        submit(entity);
//                        successIds.add(entity.getDataSourceId());
//                    }
//                } else {
//                    entity.setDataSource(YthConstant.DATA_NINGBO);
//
//                    extracted(entity);
//
//                    submit(entity);
//                    successIds.add(entity.getDataSourceId());
//                }
//            }
//        } else {
//            failReasons.add("数据为空");
//        }
//        ythResult.setSuccessIds(successIds);
//        ythResult.setFailIds(failIds);
//        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
//        //ythResult转换成json字符串
//        return JSON.toJSONString(ythResult);
//    }
//
//    /**
//     * 将数字宁波过来的数据人员id，从同步过来的人员档案中取出来，免职主表保存入库之后的人员主键数据
//     *
//     * @param entity
//     */
//    private void extracted(RemovalManagement entity) {
//        Map<String, String> orgSourceIds = orgService.getSourceId();
//        String orgId = orgSourceIds.get(entity.getCompanyNameId());
//        if (StringUtils.isNotBlank(orgId)) {
//            entity.setCompanyNameId(orgId);
//            entity.setCreateCompanyId(orgId);
//        }
//
//        StaffFiles staffFiles = staffFilesMapper.selectOne(new LambdaQueryWrapper<StaffFiles>().eq(StaffFiles::getDataSourceId, entity.getStaffNameId())
//                .eq(StaffFiles::getDataSource, 3));
//        if (Optional.ofNullable(staffFiles).isPresent()) {
//            entity.setStaffNameId(staffFiles.getId());
//        }
//        //免职子信息
//        List<RemovalPartTimeInfo> removePartTimeInfos = entity.getRemovePartTimeInfos();
//        if (CollectionUtil.isNotEmpty(removePartTimeInfos)) {
//            removePartTimeInfos.forEach(item -> {
//                if (StringUtil.isNotBlank(orgId)){
//                    item.setCreateCompanyId(orgId);
//                }
//                if (Optional.ofNullable(staffFiles).isPresent()) {
//                    item.setStaffNameId(staffFiles.getId());
//                }
//            });
//
//        }
//
//
//    }
//}
